<!--场景应用金融产品-新增编辑-->
<template>
    <div class="financialProductAdd">
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/financialProduct' }">场景应用金融产品</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='add'">新增</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='edit'">编辑</el-breadcrumb-item>
        </el-breadcrumb>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
            <el-form-item label="场景金融名称：" prop="financialSceneName">
                <el-input v-model="ruleForm.financialSceneName" class="w-320" :disabled="special"></el-input>
            </el-form-item>
            <el-form-item label="业务场景：" prop="businessScene" required>
                <el-select v-model="ruleForm.businessScene" class="w-320" :disabled="special">
                    <el-option label="新房" :value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="金融产品：" prop="financialProductId" class="no-margin">
                <el-select v-model="ruleForm.financialProductId" class="w-320" @change="productChange" :disabled="special">
                    <el-option v-for="item in productList" :label="item.productTypeName" :value="item.id" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="">
                可用额度：{{productChecked.availableCapital}}
            </el-form-item>
            <el-form-item label="城市：">
                <el-select v-model="ruleForm.cityId" class="w-320" filterable @change="loadDev">
                    <el-option v-for="item in cityList"
                               :key="item.cityId"
                               :label="item.city"
                               :value="item.cityId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="楼盘：">
                <el-select v-model="ruleForm.devId" class="w-320" filterable>
                    <el-option v-for="(item,j) in devList"
                               :key="item.devId+j"
                               :label="item.devName"
                               :value="item.devId">
                    </el-option>
                </el-select>
                <el-button type="primary" @click="addDev">添加</el-button>
            </el-form-item>
            <el-form-item label="">
                <div v-for="(x,index) in ruleForm.sceneDevs" :key="index" class="dev-item">
                    {{x.cityName}}-{{x.devName}}
                    <i class="close-icon" @click="deleteDev(index)">×</i>
                </div>
                <div class="dev-clear" @click="clearDev" v-show="ruleForm.sceneDevs.length>3">删除全部</div>
            </el-form-item>
            <el-form-item label="授信额度：" prop="lineofCredit" required>
                <el-input-number v-model="ruleForm.lineofCredit" :precision="2" :step="10000" :min="10000" :max="999999999999" class="w-320"></el-input-number>&nbsp;元
            </el-form-item>
            <el-form-item label="可用周期：" prop="availableCycle" class="no-margin" required>
                <el-input v-model="ruleForm.availableCycle" class="w-320" :disabled="special"></el-input>&nbsp;天
            </el-form-item>
            <el-form-item class="tip">
                可用周期：{{productChecked.beginCycle}}-{{productChecked.endCycle}}天
            </el-form-item>
            <el-form-item label="执行利率：" prop="interestRate" class="no-margin" required>
                <el-input v-model="ruleForm.interestRate" class="w-320" :disabled="special"></el-input>&nbsp;%
            </el-form-item>
            <el-form-item class="tip">
                风控区间：{{productChecked.beginCostControl}}%-{{productChecked.endCostControl}}%
            </el-form-item>
            <el-form-item label="适用角色：" prop="applyRole">
                <el-select v-model="ruleForm.applyRole" class="w-320" :disabled="special">
                    <el-option label="好生活" :value="1"></el-option>
                    <el-option label="经纪人" :value="2"></el-option>
                    <el-option label="经纪公司" :value="3"></el-option>
                    <el-option label="网络推客" :value="4"></el-option>
                    <el-option label="开发商" :value="5"></el-option>
                    <el-option label="合伙人" :value="6"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="利率承担方式：" prop="interestRateBearingMethod">
                <el-select v-model="ruleForm.interestRateBearingMethod" class="w-320" @change="methodChange" :disabled="special">
                    <el-option label="单独承担" :value="1"></el-option>
                    <el-option label="多方承担" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="好生活承担："
                          v-if="ruleForm.interestRateBearingMethod==1"
                          :rules="rules.needNumRule"
                          prop="sceneRates.0.shareInterestRate"
                          required
            >
                <el-input v-model="ruleForm.sceneRates[0].shareInterestRate" class="w-320" :disabled="special"></el-input>&nbsp;%
            </el-form-item>
            <el-form-item label="" v-if="ruleForm.interestRateBearingMethod==2">
                <div v-for="(item,index) in ruleForm.sceneRates" class="otherRate">
                    <el-checkbox v-model="item.able" @change="clearRate(item)" :disabled="special"></el-checkbox>
                    <span>{{item.applyRole | shareInterestRateFilter}}利率</span>
                    <el-form-item label="" :rules="rules.numRule" :prop="'sceneRates.'+index+'.shareInterestRate'">
                        <el-input v-model="item.shareInterestRate" class="w-80" :disabled="!item.able || special"></el-input>&nbsp;%
                    </el-form-item>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button @click="pageBack">取消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">发布</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

export default {
    name:"financialProductAdd",
    created() {
        this.pageType = this.$route.query.type
        if(this.pageType=='add'){
            this.loadProductList()
        }
        this.loadCity()
        if(this.pageType=='edit'){
            this.id = this.$route.query.id
            this.special = this.$route.query.special
            this.$axios.post('/financialCenter/financeProduct/scene/detail',{sceneId: this.$route.query.id}).then(res=>{
                this.ruleForm = Object.assign(this.ruleForm,res.list[0])
                this.$axios.post('/financialCenter/financeProduct/list',{pageNum:1,pageSize:999}).then(res=>{
                    this.productList = res.list
                    this.productChecked = this.productList.find(item=>item.id==this.ruleForm.financialProductId)
                })
            })
        }
    },
    mounted() {},
    components: {},
    filters: {
        shareInterestRateFilter(val){
            if(val==1){
                return '好生活'
            }else if(val==2){
                return '经纪人'
            }else if(val==3){
                return '经纪公司'
            }else if(val==4){
                return '网络推客'
            }else if(val==5){
                return '开发商'
            }else if(val==6){
                return '合伙人'
            }
        }
    },
    data() {
        return {
            pageType: '',
            special: false,// 特殊情况的编辑，只能编辑楼盘和授信额度
            productList: [],
            productChecked: {},
            cityList: [],
            devList: [],
            ruleForm:{
                cityId: '',//表单不需要提交的时候删除
                devId: '',//表单不需要提交的时候删除
                financialSceneName:'',// 场景金融名称
                businessScene:1, // 业务场景
                financialProductId:'', // 金融产品
                lineofCredit:10000, // 授信额度
                availableCycle: '',// 可用周期
                interestRate:'',// 执行利率
                applyRole: '',
                interestRateBearingMethod: '', // 利率承担方式
                sceneDevs:[], // 楼盘
                sceneRates: [
                    {able:true,applyRole:1,shareInterestRate:''},
                ], // 承担利率
            },
            sceneRatesOne:[{able:true,applyRole:1,shareInterestRate:''}],
            sceneRatesTemp: [
                {able:false,applyRole:1,shareInterestRate:''},
                {able:false,applyRole:2,shareInterestRate:''},
                {able:false,applyRole:3,shareInterestRate:''},
                {able:false,applyRole:4,shareInterestRate:''},
                {able:false,applyRole:5,shareInterestRate:''},
                {able:false,applyRole:6,shareInterestRate:''},
            ],
            rules:{
                financialSceneName: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ],
                financialProductId:[
                    { required: true, message: '请选择金融产品', trigger: 'change' },
                ],
                availableCycle:[
                    {validator: (rule,value,callback)=>{
                        if(!value){
                            callback(new Error('请输入可用周期'))
                        }
                        if(!/^\d*$/.test(value)){
                            callback(new Error('只能输入正整数'))
                        }
                        callback()
                    }}
                ],
                interestRate:[
                    {validator:(rule,value,callback)=>{
                            if(!value){
                                callback(new Error('请输入执行效率'))
                            }
                            if(!/^\d*(\.\d{1,2})?$/.test(value)){
                                callback(new Error('只能有两位小数'))
                            }
                            callback()
                        }}
                ],
                numRule:[
                    {validator:(rule,value,callback)=>{
                            if(value||value==0){
                                if(!/^\d*(\.\d{1,2})?$/.test(value)){
                                    callback(new Error('只能有两位小数'))
                                }
                                if(value>100){
                                    callback(new Error('不能大于100'))
                                }
                            }
                            callback()
                        }}
                ],
                needNumRule:[
                    {validator:(rule,value,callback)=>{
                            if(!value){
                                callback(new Error('请填写好生活利率'))
                            }
                            if(!/^\d*(\.\d{1,2})?$/.test(value)){
                                callback(new Error('只能有两位小数'))
                            }
                            if(value>100){
                                callback(new Error('不能大于100'))
                            }
                            callback()
                        }}
                ],
                applyRole:[
                    { required: true, message: '请选择适用角色', trigger: 'change' },
                ],
                interestRateBearingMethod:[
                    { required: true, message: '请选择利率承担方式', trigger: 'change' },
                ]
            }
        }
    },
    methods: {
        loadProductList(){
            this.$axios.post('/financialCenter/financeProduct/list',{pageNum:1,pageSize:999}).then(res=>{
                this.productList = res.list
            })
        },
        productChange(){
            if(this.ruleForm.financialProductId){
                this.productChecked = this.productList.find(item => item.id == this.ruleForm.financialProductId)
            }
        },
        loadCity() {
            this.$axios.post('/city/cityList').then(res => {
                this.cityList = res.cityList
            });
        },
        loadDev() {
            this.ruleForm.devId = ''
            this.$axios.post('estate/devs/select/mapParam',{cityId: this.ruleForm.cityId}).then(res => {
                this.devList = res;
            });
        },
        addDev() {
            if(this.ruleForm.devId){
                let {city:cityName, cityId: cityId} = this.cityList.find(it => it.cityId == this.ruleForm.cityId);
                let {devName: devName, devId: devId} = this.devList.find(it => it.devId == this.ruleForm.devId);
                if (!this.ruleForm.sceneDevs.find(it => it.devId == devId)) {
                    this.ruleForm.sceneDevs.push({
                        devId: devId,
                        devName: devName,
                        cityId:cityId,
                        cityName: cityName
                    });
                    this.$message.success('添加成功')
                } else {
                    this.$message.error('该楼盘已绑定，请勿重复绑定')
                }
            } else {
                if (!this.ruleForm.cityId) {
                    this.$message.info('请选择城市');
                    return;
                }
                let {city:cityName, cityId: cityId} = this.cityList.find(it => it.cityId == this.ruleForm.cityId);
                this.devList.forEach(item=>{
                    if (!this.ruleForm.sceneDevs.find(it => it.devId == item.devId)) {
                        this.ruleForm.sceneDevs.push({
                            devId: item.devId,
                            devName: item.devName,
                            cityId:cityId,
                            cityName: cityName
                        });
                    }
                })
                if(this.ruleForm.sceneDevs.length>0){
                    this.$message.success('添加成功')
                }
            }
        },
        clearDev(){
            this.ruleForm.sceneDevs = []
        },
        deleteDev(index) {
            this.ruleForm.sceneDevs.splice(index, 1);
            this.$message.success('删除成功')
        },
        clearRate(item){
            if(item.able==false){
                item.shareInterestRate = ''
            }
        },
        // 利率承担方式改变
        methodChange(){
            if(this.ruleForm.interestRateBearingMethod==1){
                this.ruleForm.sceneRates = JSON.parse(JSON.stringify(this.sceneRatesOne))
            }else{
                // 切换了承担方式后，去掉了对好生活承担的校验，否则会影响多方承担
                this.$refs.ruleForm.clearValidate('sceneRates.0.shareInterestRate');
                this.ruleForm.sceneRates = JSON.parse(JSON.stringify(this.sceneRatesTemp))
            }
        },
        pageBack(){
            this.$router.back()
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let param = JSON.parse(JSON.stringify(this.ruleForm))
                    delete param.devId
                    delete param.cityId
                    param.operatorId = JSON.parse(localStorage.getItem('cmsUser')).userId
                    param.operatorName = JSON.parse(localStorage.getItem('cmsUser')).name
                    if(param.sceneDevs.length==0){
                        this.$message.error('楼盘不可为空')
                        return
                    }
                    if(param.interestRateBearingMethod==2){
                        let sum = 0
                        param.sceneRates.forEach(item=>{
                            sum += Number(item.shareInterestRate)
                        })
                        if(sum!=param.interestRate){
                            this.$message.error('多方承担利率相加需等于执行利率')
                            return
                        }
                    }
                    if(this.pageType=='add'){
                        this.$axios.post('/financialCenter/financeProduct/scene/save',param).then(res=>{
                            this.$message.success('发布成功')
                            this.$router.push({path: '/financialProduct'})
                        })
                    }else {
                        param.id = this.id
                        if(this.special){// 特殊情况的编辑
                            this.$axios.post('/financialCenter/financeProduct/scene/updateAmount',param).then(res=>{
                                this.$message.success('发布成功')
                                this.$router.push({path: '/financialProduct'})
                            })
                        }else{
                            this.$axios.post('/financialCenter/financeProduct/scene/save',param).then(res=>{
                                this.$message.success('发布成功')
                                this.$router.push({path: '/financialProduct'})
                            })
                        }
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    },
    computed: {}
}
</script>
<style lang="stylus" scoped>
    .financialProductAdd {
        .dev-item {
            background: #67C23A;
            float: left;
            margin: 0 15px 8px 0;
            position: relative;
            border-radius: 4px;
            color: #fff;
            padding: 0 23px 0 10px;
            i.close-icon {
                position: absolute;
                right: 5px;
                top: 1px;
                line-height: 1;
                color: #fff;
                font-style: normal;
                cursor: pointer;
                font-size: 24px;
            }
        }
        .dev-clear{
            float: left;
            background: #f00;
            margin: 0 15px 8px 0;
            padding:0 5px;
            color: #fff;
            border-radius: 4px;
            cursor: pointer;
        }
        .otherRate{
            display: flex;
            margin-bottom: 20px;
            span{
                display: inline-block;
                width: 100px;
            }
        }
    }
</style>
<style>
    .financialProductAdd .el-form-item.no-margin{
        margin-bottom: 5px;
    }
    .tip .el-form-item__content{
        color: #444;
    }
</style>
